class Cart{
    constructor(){
        this.otbody = document.getElementsByTagName("tbody")[0];
        this.topDel = document.getElementById("topDel");
        this.allNum = document.getElementById("allNum");
        this.allPrice = document.getElementById("allPrice");
        this.checkAll = document.getElementById("defaultCheck1");
        this.checkArr = [];
        this.url = "data/goods.json";
        this.logGuard();
        this.load();
        this.addEvent();
    }
    logGuard(){
        let userObj = sessionStorage.getItem("token") ? JSON.parse(sessionStorage.getItem("token")) : {};
        if(userObj.isLogin !== "ok"){
            window.location.href = "login.html";
        }
    }
    checkListRender(){
        if(this.checkAll.firstElementChild.checked){
            for(let i=0;i<this.shopData.length;i++){
                this.checkArr.push(this.shopData[i].id)
            }
        }else{
            this.checkArr = [];
        }
        //取消全部勾选
        for(let i=0;i<this.trList.length;i++){
            this.trList[i].firstElementChild.querySelector("div input").checked = false;
        }
        //全部选中
        this.checkArr.forEach(val=>{
            for(let i=0;i<this.trList.length;i++){
                if(this.trList[i].getAttribute("data-id")===val){
                    this.trList[i].firstElementChild.querySelector("div input").checked = true;
                }
            }
        })
    }
    addEvent(){
        var that = this;
        this.otbody.addEventListener("click",function(eve){
            var e = eve || window.event;
            var tar = e.target || e.srcElement;
            if(tar.getAttribute("data-del")==="delete"){
                var parentTr = tar.parentNode.parentNode;
                that.id = parentTr.getAttribute("data-id");
                parentTr.remove();
                that.setData(0);
            }
            //单个复选框选中
            if(tar.type==="checkbox"){
                var flag = true;
                for(let i =0;i<that.trList.length;i++){
                    if(!that.trList[i].firstElementChild.querySelector("div input").checked){
                        flag = false;
                        break;
                    } 
                }
                if(flag){
                    that.checkAll.firstElementChild.checked = true;
                }else{
                    that.checkAll.firstElementChild.checked = false;
                }
                var i = tar.parentNode.parentNode.parentNode.getAttribute("data-id");
                if(tar.checked){
                    that.checkArr.push(i);
                }else{
                    that.checkArr.splice(that.checkArr.indexOf(i),1)
                }
            }
        })
        this.otbody.addEventListener("input",function(eve){
            var e = eve || window.event;
            var tar = e.target || e.srcElement;
            if(tar.className==="changeNum"){
                that.num = tar.value;
                that.id = tar.parentNode.parentNode.getAttribute("data-id");
                tar.parentNode.nextElementSibling.innerHTML = 
                (Number(tar.parentNode.previousElementSibling.innerHTML)*Number(that.num)).toFixed(2)
                // parseFloat(parseFloat(tar.parentNode.previousElementSibling.innerHTML) * that.num);
                that.setData(1);
            }
        })
        //全选按钮
        this.checkAll.addEventListener("click",function(){
            that.checkListRender();
        })
        
        //顶部删除按钮
        this.topDel.addEventListener("click",function(){
            that.checkArr.forEach(val=>{
                for(let i=0;i<that.trList.length;i++){
                    if(that.trList[i].getAttribute("data-id")===val){
                        that.trList[i].remove();
                        that.setDataChecked();
                    }
                }
            })
        })
    }
    setData(type){
        let i = 0;
        this.shopData.some((val,idx)=>{
            i = idx;
            return val.id===this.id;
        })
        if(type===0){
            this.shopData.splice(i,1);
        }else{
            this.shopData[i].num = this.num;
        }
        localStorage.setItem("shopData",JSON.stringify(this.shopData));
        this.headRender();
    }
    setDataChecked(){
        this.shopData.forEach((val1,idx)=>{
            this.checkArr.forEach(val2=>{
                if(val1.id===val2){
                    this.shopData.splice(idx,1);
                }
            })
        })
        localStorage.setItem("shopData",JSON.stringify(this.shopData));
        this.headRender();
    }
    load(){
        $.ajax({
            url:this.url,
            success:(res)=>{
                this.res = JSON.parse(res);
                this.getData();
            }
        })
    }
    getData(){
        this.shopData = localStorage.getItem("shopData") ? JSON.parse(localStorage.getItem("shopData")) : [];
        this.render();
    }
    render(){
        var str = "";
        this.shopData.forEach((val1,idx) => {
            this.res.forEach(val2=>{
                if(val1.id===val2.goodsId){
                    str += `<tr data-id="${val1.id}">
                    
                    <td><div class="form-check"><input class="form-check-input" type="checkbox"></div></td>
                                <td class="td-img"><img src="${val2.img}" alt=""></td>
                                <td>${val2.name}</td>
                                <td>${val2.price}</td>
                                <td><input type="number" min="1" value="${val1.num}" class="changeNum"></td>
                                <td>${val2.price * val1.num}</td>
                                <td>
                                    <span class="btn btn-info" data-del="delete">删除</span>
                                </td>
                            </tr>`
                }
            })
        });
        this.otbody.innerHTML = str;
        this.trList = this.otbody.querySelectorAll("tr");
        this.headRender();
    }
    headRender(){
        var sum1 =0; var sum2 = 0;
        this.shopData.forEach(val1=>{
            this.res.forEach(val2=>{
                if(val1.id===val2.goodsId){
                    sum1 = sum1 + parseInt(val1.num);
                    sum2 = sum2 + ((Number(val1.num)*Number(val2.price)).toFixed(2))*1;
                }
            })
        })
        this.allNum.value = sum1;
        this.allPrice.value = sum2;
   }
}
new Cart;